
import sys
import indexing.featureindex
from summaryprocessor import SummaryProcessor, SinglePositionProcessor, SkipZeroes


class Counts(SinglePositionProcessor):
  def __str__(self):
    return str(self.total)

class WeightedCounts(SinglePositionProcessor):
  
  def __init__(self):
    SinglePositionProcessor.__init__(self)
    self.weightedCounts = 0.0
    
  def incr(self, base, seqpos, details):
    SinglePositionProcessor.incr(self, base, seqpos, details)
    weight = 1
    if details.qual == "NA" and details.ubOk != "Y":
      weight = 0
    else:
      mappingLocs = sum([int(x) for x in details.qualCounts.split(":")])
      if mappingLocs>1:
        weight = 1.0/mappingLocs
    self.weightedCounts += weight

    def __str__(self):
      return "%d\t%f" % (self.total, self.weightedCounts)

def process(query, indexFilename, skipZeroes=(SkipZeroes.LEFT | SkipZeroes.RIGHT)):
  processor = SummaryProcessor(Counts)
  return processor.process(query, indexFilename, skipZeroes)

def printUsage(args, usage, minArgs=2):
  if len(args) < minArgs or args[1].startswith("-h") or args[1].startswith("--h"):
    print usage
    sys.exit(1)

usageString = """
Usage: python %s INDEX_FILE CHR MIN_POS MAX_POS

Prints the sum of mapping weights in the specified summary file at each position
in the query.
Mapping weights are 1/N for each mapping, where N is the number of locations
to which the read was mapped.
"""

if __name__=="__main__":
  printUsage(sys.argv, usageString % sys.argv[0], 3)
  indexFilename = sys.argv[1]
  qchr = sys.argv[2]
  qmin = long(sys.argv[3])
  qmax = long(sys.argv[4])
  query = (qchr, '?', qmin, qmax)
  for (x, cts) in process(query, indexFilename, SkipZeroes.ALL):
    print "%s\t%s\t%s" % (qchr, x, str(cts))

